﻿using System;
using System.Collections.Generic;
using System.Text;

namespace csharpcore7_ch3Inherite
{
    /// <summary>
    /// 资产类
    /// </summary>
    class Asset
    {
        public string Name;       
    }
    class Stock : Asset
    {
        public long SharesOwned; //拥有的股份
    }
    class House : Asset {
        public decimal Mortgage; //抵押贷款
    }

    class Chapt03_2Inherite
    {
        static void _Main()
        {
            Stock msft = new Stock
            {
                Name = "MSFT",
                SharesOwned = 1000
            };
            Console.WriteLine(msft.Name);
            Console.WriteLine(msft.SharesOwned);

            House mansion = new House
            {
                Name = "Mansion",//大厦
                Mortgage = 250000
            };
            Console.WriteLine(mansion.Name);
            Console.WriteLine(mansion.Mortgage);

            //多态-程序拥有了多个运行状态
            static void Display(Asset asset)
            {
                Console.WriteLine(asset.Name);
            }
            Display(msft);
            Display(mansion);

            //向下类型转换
            Asset a = msft;         //向上类型转换
            Stock s  = (Stock)a;   //向下类型转换a和s都指向msft这个对象，但a 和s 类型不同。
            Console.WriteLine(s.SharesOwned); //1000
            Console.WriteLine(s == a);        //True
            Console.WriteLine(s == msft);      //True

            //向下类型转换导致运行错误，必须显式转换
            House h = new House();
             a = h;    //向上类型转换总是成功的
             //s = (Stock)a; //向下转换失败，a是House,不是Stock。会抛出InvalidCastException


            //as操作符
            a = msft;           
            s = a as Stock;
            if (s != null) Console.WriteLine(s.SharesOwned);
            a = mansion;
            //把a转换为Stock类型，a指向的类型为House,转换出错
            s = a as Stock;         //as运行符在向下类型转换出错时返回null(而不是抛出异常)
            if (s != null)
                Console.WriteLine(s.SharesOwned);
            else {
                Console.WriteLine("s为null");
            }
            // long x = 3 as long;//as运行符不能用于实现自定义转换，也不能用于数值转换


            //is操作符
            a = msft;
            if (a is Stock)
                Console.WriteLine(((Stock)a).SharesOwned);
            else {
                Console.WriteLine("a不是Stock类型");
            }

            //is操作符与模式变量 C#7引入模式变量
            if (a is Stock s1)
                Console.WriteLine(s1.SharesOwned);
            //等价下面的代码
            //Stock s1;
            //    if (a is Stock)
            //{
            //    s1 = (Stock)a;
            //    Console.WriteLine(((Stock)a).SharesOwned);
            //}

            if (a is Stock s2 && s2.SharesOwned > 100000) //引入变量可以立即使用
                Console.WriteLine("Wealthy");
            else //引入变量在is表达式之外依然在作用域内。           
                s2 = new Stock();

            Console.WriteLine(s2.SharesOwned);             
        }       
    }
}
